﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using UnityEditor;

public class Object_editor : UnityEditor.EditorWindow
{
    protected static ObjectsInfo prop_info;
    protected static BuffInfo buff_info;
    protected static CraftTableInfo craft_info;
    private string text;
    private string search_content = "";// 搜索内容
    private Vector2 ScrollPos;

    private bool Prop_info_show = false;
    private int Setting_index = 0;
    private int index = 101;
    private int temp_index = 101;
    private bool ID_Warning = false;

    private bool[] isDisplay;
    private Vector2[] ChooseScrollPosition;

    private void Awake()
    {
        isDisplay = new bool[9];
        ChooseScrollPosition = new Vector2[9];
        for (int i = 0; i < 9; i++) isDisplay[i] = false;
    }

    private void OnEnable()
    {
    }

    [MenuItem("Tools/Object_Editor")]
    static void Create()
    {
        AssetDatabase.Refresh();
        EditorWindow.GetWindowWithRect(typeof(Object_editor), new Rect(0, 0, 800, 600));
        GameObject obj = GameObject.Find("ObjectSystem");
        prop_info = obj.GetComponent<ObjectsInfo>();
        buff_info = obj.GetComponent<BuffInfo>();
        craft_info = obj.GetComponent<CraftTableInfo>();

        prop_info.ReadInfo();
        buff_info.ReadInfo();
        craft_info.ReadInfo();
        //prop_info = GameObject.Find("ObjectSyetem").GetComponent<ObjectsInfo>();
        /*if (Selection.activeTransform != null)
        {
            prop_info = Selection.activeTransform.GetComponent<ObjectsInfo>();
            buff_info = Selection.activeTransform.GetComponent<BuffInfo>();
            craft_info = Selection.activeTransform.GetComponent<CraftTableInfo>();

            prop_info.ReadInfo();
            buff_info.ReadInfo();
            craft_info.ReadInfo();
        }*/
    }    

    private void OnGUI()
    {
        EditorGUILayout.BeginVertical();
        string[] Edit_item = { "Buff", "道具", "合成表" };
        Setting_index = GUILayout.Toolbar(Setting_index, Edit_item);
        EditorGUILayout.BeginHorizontal();

        // buff信息
        if(Setting_index == 0)
        {
            EditorGUILayout.BeginVertical("GroupBox", GUILayout.Width(300), GUILayout.Height(500));
            EditorGUILayout.BeginHorizontal();
            search_content = EditorGUILayout.TextField("", search_content, "SearchTextField");
            if(GUILayout.Button("+", GUILayout.Width(20)))
            {
                // 添加新的代码
                index = buff_info.CreateNewBuff();
                temp_index = index;
                buff_info.Sort_BUFF_Dic();
            }
            EditorGUILayout.EndHorizontal();

            ScrollPos = EditorGUILayout.BeginScrollView(ScrollPos);
            foreach (Buff key_pair in buff_info.buff_dic) 
            {
                if (!key_pair.tag.Contains(search_content)) continue;
                EditorGUILayout.BeginHorizontal();
                if(GUILayout.Button("[ID:" + key_pair.id + "]" + key_pair.tag, GUILayout.Width(250)))
                {
                    index = key_pair.id;
                    temp_index = index;
                }
                if (GUILayout.Button("X", GUILayout.Width(20)))
                {
                    buff_info.buff_dic.Remove(key_pair);
                    buff_info.Sort_BUFF_Dic();
                    return;
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();

            Buff info = buff_info.getBuffInfobyid(index);
            if (info != null)
            {
                EditorGUILayout.BeginVertical("GroupBox", GUILayout.Width(350));
                //info.id = EditorGUILayout.DelayedIntField("ID:", info.id);
                temp_index = EditorGUILayout.DelayedIntField("ID:", temp_index);// 先获得临时的id
                if(buff_info.Check_ID_if_Exist(temp_index) >= 0 && temp_index != info.id)// 如果设置的ID已经存在
                {
                    ID_Warning = true;
                }
                else
                {
                    ID_Warning = false;
                    index = temp_index;
                    info.id = temp_index;
                    buff_info.Sort_BUFF_Dic();
                }
                info.tag = EditorGUILayout.TextField("标签", info.tag);
                info.lasttime = EditorGUILayout.FloatField("默认持续时间(s)：", info.lasttime);
                if(info.bleed_interval == 0)
                    info.bleed_interval = EditorGUILayout.FloatField("流血间隔(s) (无·效·果)：", info.bleed_interval);
                else
                    info.bleed_interval = EditorGUILayout.FloatField("流血间隔(s)：", info.bleed_interval);
                if(info.battle_update == 0)
                    info.battle_update = EditorGUILayout.FloatField("战力修正(%) (无·效·果)：", info.battle_update);
                else
                    info.battle_update = EditorGUILayout.FloatField("战力修正(%)：", info.battle_update);
                if(info.vol_update == 0)
                    info.vol_update = EditorGUILayout.FloatField("速度修正(%) (无·效·果)：", info.vol_update);
                else
                    info.vol_update = EditorGUILayout.FloatField("速度修正(%)：", info.vol_update);
                if(info.radiation_update == 0)
                    info.radiation_update = EditorGUILayout.FloatField("辐射度修正(%) (无·效·果):", info.radiation_update);
                else
                    info.radiation_update = EditorGUILayout.FloatField("辐射度修正(%):", info.radiation_update);

                if(ID_Warning)
                {
                    EditorGUILayout.HelpBox("当前使用的ID已经存在，默认ID为:" + info.id.ToString(), MessageType.Error);
                }

                EditorGUILayout.EndVertical();
            }
        }
        // 如果选中的道具信息
        else if(Setting_index == 1)
        {
            EditorGUILayout.BeginVertical("GroupBox", GUILayout.Width(300), GUILayout.Height(500));

            EditorGUILayout.BeginHorizontal();
            search_content = EditorGUILayout.TextField(search_content, new GUIStyle("SearchTextField"));
            if (GUILayout.Button("+", GUILayout.Width(20)))
            {
                // 添加新的代码
                index = prop_info.CreateAnother();
                temp_index = index;
                prop_info.Sort_OBJ_Dic();
            }
            EditorGUILayout.EndHorizontal();

            ScrollPos = EditorGUILayout.BeginScrollView(ScrollPos);
            foreach (Objectinfo key_pair in prop_info.object_dic)
            {
                if (!key_pair.name.Contains(search_content)) continue;
                GUIContent prop_content;
                Sprite prop_sprite = LoadSpriteInAsset(key_pair.atlas_path, key_pair.icon_name);

                if(prop_sprite != null)
                {
                    Texture2D prop_image = Sprite_To_Texture(prop_sprite);
                    prop_content = new GUIContent("  [ID:" + key_pair.id + "]" + key_pair.name, prop_image);
                }
                else
                {
                    prop_content = new GUIContent("  [ID:" + key_pair.id + "]" + key_pair.name);
                }

                EditorGUILayout.BeginHorizontal();
                //if(GUILayout.Button("[ID:" + key_pair.Key + "]" + key_pair.Value.name, GUILayout.Width(250)))
                if(GUILayout.Button(prop_content, GUILayout.Width(250)))
                {
                    index = key_pair.id;
                    temp_index = index;
                }
                if(GUILayout.Button("X", GUILayout.Width(20)))
                {
                    prop_info.object_dic.Remove(key_pair);
                    prop_info.Sort_OBJ_Dic();
                    return;
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();

            Objectinfo info = prop_info.getObjectinfobyid(index);
            if (info != null)
            {
                EditorGUILayout.BeginVertical("GroupBox", GUILayout.Width(350));
                EditorGUILayout.BeginHorizontal();

                string Sprite_Path = "";
                Sprite ObjSprite = null;
                ObjSprite = LoadSpriteInAsset(info.atlas_path, info.icon_name);

                ObjSprite = EditorGUILayout.ObjectField("", ObjSprite, typeof(Sprite), false, GUILayout.Width(80)) as Sprite;
                if (ObjSprite != null)
                {
                    info.icon_name = ObjSprite.name;
                    Sprite_Path = AssetDatabase.GetAssetPath(ObjSprite);// 获得Sprite地址
                    Sprite_Path = Sprite_Path.Substring(17);
                    int suffix_index = Sprite_Path.LastIndexOf(".");
                    int last_file_index = Sprite_Path.LastIndexOf("/");
                    //Debug.Log(suffix_index + " , " + last_file_index);
                    //Debug.Log(Sprite_Path.Substring(0, suffix_index));
                    if(suffix_index >= 0 && last_file_index < suffix_index)
                    {
                        Sprite_Path = Sprite_Path.Substring(0, suffix_index);
                    }
                    info.atlas_path = Sprite_Path;
                    //Debug.Log(Sprite_Path);
                }
                EditorGUILayout.BeginVertical();
                temp_index = EditorGUILayout.DelayedIntField("ID:", temp_index);
                if(prop_info.Check_info_is_Existed(temp_index) >= 0 && temp_index != info.id)
                {
                    ID_Warning = true;
                }
                else
                {
                    ID_Warning = false;
                    index = temp_index;
                    info.id = temp_index;
                    prop_info.Sort_OBJ_Dic();
                }
                info.name = EditorGUILayout.TextField("名称:", info.name);
                info.str_type = (Objecttype)EditorGUILayout.EnumPopup("种类：", info.str_type);
                info.weight = EditorGUILayout.IntField("质量", info.weight);
                EditorGUILayout.EndVertical();
                EditorGUILayout.EndHorizontal();
                EditorGUILayout.LabelField("描述：");
                info.describe = EditorGUILayout.TextArea(info.describe, GUILayout.Height(50));
                if (info.str_type == Objecttype.drug)
                {
                    if (Prop_info_show = EditorGUILayout.Foldout(Prop_info_show, "药品/食物数据"))
                    {
                        info.hp = EditorGUILayout.IntField("回复血量：", info.hp);
                        info.radiation = EditorGUILayout.IntField("辐射度变动量：", info.radiation);
                        info.food = EditorGUILayout.IntField("饱食度：", info.food);
                        info.water = EditorGUILayout.IntField("饱水度：", info.water);

                        int Obtain_Buff_index = buff_info.Check_ID_if_Exist(info.cause_buffID);
                        Obtain_Buff_index = EditorGUILayout.Popup("使用后会获得的buff:", Obtain_Buff_index + 1, buff_info.ToList());
                        Obtain_Buff_index--;
                        EditorGUILayout.BeginVertical("HelpBox");
                        if (Obtain_Buff_index >= 0)
                        {
                            Buff cause_buff = buff_info.buff_dic[Obtain_Buff_index];
                            info.cause_buffID = cause_buff.id;
                            List<string> brief_infos = cause_buff.BriefInfo();
                            foreach (string one_info in brief_infos)
                            {
                                EditorGUILayout.LabelField(one_info);
                            }
                        }
                        else
                        {
                            info.cause_buffID = 0;
                            EditorGUILayout.LabelField("没有这个Buff！");
                        }
                        EditorGUILayout.EndVertical();
                        
                        int Defuse_Buff_index = buff_info.Check_ID_if_Exist(info.defuse_buffID);
                        Defuse_Buff_index = EditorGUILayout.Popup("使用后会失去的buff", Defuse_Buff_index + 1, buff_info.ToList());
                        Defuse_Buff_index--;
                        EditorGUILayout.BeginVertical("HelpBox");
                        if(Defuse_Buff_index >= 0)
                        {
                            Buff defuse_buff = buff_info.buff_dic[Defuse_Buff_index];
                            info.defuse_buffID = defuse_buff.id;
                            List<string> brief_infos = defuse_buff.BriefInfo();
                            foreach (string one_info in brief_infos)
                            {
                                EditorGUILayout.LabelField(one_info);
                            }
                        }
                        else
                        {
                            info.defuse_buffID = 0;
                            EditorGUILayout.LabelField("没有这个Buff！");
                        }
                        EditorGUILayout.EndVertical();
                    }
                }
                else if (info.str_type == Objecttype.equipment)
                {
                    if (Prop_info_show = EditorGUILayout.Foldout(Prop_info_show, "装备数据"))
                    {
                        info.equip_Type = (Equip_type)EditorGUILayout.EnumPopup("装备种类:", info.equip_Type);
                        info.damage = EditorGUILayout.IntField("装备伤害：", info.damage);
                        info.coldtime = EditorGUILayout.FloatField("装备cd：", info.coldtime);
                        info.armor = EditorGUILayout.IntField("护甲：", info.armor);
                        info.anti_rad = EditorGUILayout.IntField("辐射接受度(%)：", info.anti_rad);
                        info.ammo = EditorGUILayout.IntField("弹药（暂时不用）:", info.ammo);
                    }
                }
                else if (info.str_type == Objecttype.material)
                {
                    if (Prop_info_show = EditorGUILayout.Foldout(Prop_info_show, "材料数据"))
                    {

                    }
                }

                if (ID_Warning)
                {
                    EditorGUILayout.HelpBox("当前使用的ID已经存在，默认ID为:" + info.id.ToString(), MessageType.Error);
                }

                EditorGUILayout.EndVertical();
            }
        }
        // 合成表信息
        else if(Setting_index == 2)
        {
            EditorGUILayout.BeginVertical("GroupBox", GUILayout.Width(300), GUILayout.Height(500));
            EditorGUILayout.BeginHorizontal();
            search_content = EditorGUILayout.TextField(search_content, new GUIStyle("SearchTextField"));
            if (GUILayout.Button("+", GUILayout.Width(20)))
            {
                // 添加新的代码,并获得新道具的代码
                index = craft_info.Create_new_craft();
                temp_index = index;
                craft_info.Sort_Craft_List();
            }
            EditorGUILayout.EndHorizontal();
            ScrollPos = EditorGUILayout.BeginScrollView(ScrollPos);
            foreach (CraftTable one_craft in craft_info.CraftTable_dic)
            {
                Objectinfo Target_obj = prop_info.getObjectinfobyid(one_craft.targetid);
                if ( Target_obj != null && !Target_obj.name.Contains(search_content)) continue;
                EditorGUILayout.BeginHorizontal();
                GUIContent craft_content;
                if(Target_obj == null)
                {
                    craft_content = new GUIContent("无意义合成表[ID:" + one_craft.id + "]");
                }
                else
                {
                    Sprite craft_target_sprite = LoadSpriteInAsset(Target_obj.atlas_path, Target_obj.icon_name);// 合成目标的Sprite
                    if (craft_target_sprite != null)
                        craft_content = new GUIContent(" [ID:" + one_craft.id + "]" + Target_obj.name + "的合成表", Sprite_To_Texture(craft_target_sprite));
                    else
                        craft_content = new GUIContent("未完成的合成表[ID:" + one_craft.id + "]");
                }
                if(GUILayout.Button(craft_content, GUILayout.Width(250)))
                {
                    index = one_craft.id;
                    temp_index = index;
                }
                if(GUILayout.Button("X", GUILayout.Width(20)))
                {
                    craft_info.CraftTable_dic.Remove(one_craft);
                    craft_info.Sort_Craft_List();
                    return;
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();

            CraftTable info = craft_info.getCraftinfobyid(index);
            if (info != null)
            {
                EditorGUILayout.BeginVertical("GroupBox", GUILayout.Width(350));
                temp_index = EditorGUILayout.DelayedIntField("合成表id：", temp_index);
                if(temp_index != info.id && craft_info.Check_info_is_Existed(temp_index) >= 0)
                {
                    ID_Warning = true;
                }
                else
                {
                    ID_Warning = false;
                    index = temp_index;
                    info.id = temp_index;
                    craft_info.Sort_Craft_List();
                }
                info.targetid = EditorGUILayout.IntField("打造完成的物品id：", info.targetid);
                Objectinfo Targetobj = prop_info.getObjectinfobyid(info.targetid);

                EditorGUILayout.BeginVertical("HelpBox");
                if (Targetobj != null)
                {
                    Sprite targetSprite = LoadSpriteInAsset(Targetobj.atlas_path, Targetobj.icon_name);
                    if (targetSprite != null)
                    {
                        EditorGUILayout.BeginHorizontal();
                        Texture2D target_texture = Sprite_To_Texture(targetSprite);
                        GUILayout.Label(target_texture);
                        EditorGUILayout.BeginVertical();
                        EditorGUILayout.LabelField("名称:" + Targetobj.name);
                        EditorGUILayout.LabelField("类型：" + Targetobj.Get_Obj_Type());
                        EditorGUILayout.EndVertical();
                        EditorGUILayout.EndHorizontal();
                        EditorGUILayout.LabelField("描述: " + Targetobj.describe);
                    }
                    else
                    {
                        EditorGUILayout.LabelField("未设置对应的Sprite");
                        EditorGUILayout.LabelField("名称:" + Targetobj.name);
                        EditorGUILayout.LabelField("类型：" + Targetobj.Get_Obj_Type());
                        EditorGUILayout.LabelField("描述: " + Targetobj.describe);
                    }
                }
                else EditorGUILayout.LabelField("未找到对应的道具");
                EditorGUILayout.EndVertical();

                EditorGUILayout.LabelField("需要的道具种类：" + info.num_type.ToString());

                EditorGUILayout.BeginVertical();
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("所需要素材列表：");
                if (GUILayout.Button("+"))
                {
                    // 添加一个新的素材项目
                    info.num_type += 1;
                    info.mat_id.Add(-1);
                    info.mat_num.Add(1);
                }
                EditorGUILayout.EndHorizontal();
                for (int i = 0; i < info.num_type; i++)
                {
                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button("[ID: " + info.mat_id[i].ToString() + "]", GUILayout.Width(250)))
                        isDisplay[i] = !isDisplay[i];
                    GUILayout.Label("*");
                    info.mat_num[i] = EditorGUILayout.IntField(info.mat_num[i]);
                    if (GUILayout.Button("X", GUILayout.Width(20)))
                    {
                        // 这是删除这个素材的部分函数
                        info.num_type -= 1;
                        info.mat_id.RemoveAt(i);
                        info.mat_num.RemoveAt(i);
                        return;
                    }
                    EditorGUILayout.EndHorizontal();
                    if (isDisplay[i])
                    {
                        EditorGUILayout.BeginVertical();
                        Debug.Log(info.mat_id[i]);
                        info.mat_id[i] = EditorGUILayout.IntField("物品id：", info.mat_id[i]);
                        ChooseScrollPosition[i] = EditorGUILayout.BeginScrollView(ChooseScrollPosition[i], GUILayout.Height(100));
                        foreach(Objectinfo OBJINFO in prop_info.object_dic)
                        {
                            if (!OBJINFO.name.Contains(search_content)) continue;
                            GUIContent prop_content;
                            Sprite prop_sprite = LoadSpriteInAsset(OBJINFO.atlas_path, OBJINFO.icon_name);

                            if (prop_sprite != null)
                            {
                                Texture2D prop_image = Sprite_To_Texture(prop_sprite);
                                prop_content = new GUIContent("  [ID:" + OBJINFO.id + "]" + OBJINFO.name, prop_image);
                            }
                            else
                            {
                                prop_content = new GUIContent("  [ID:" + OBJINFO.id + "]" + OBJINFO.name);
                            }

                            EditorGUILayout.BeginHorizontal();
                            //if(GUILayout.Button("[ID:" + key_pair.Key + "]" + key_pair.Value.name, GUILayout.Width(250)))
                            if (GUILayout.Button(prop_content, GUILayout.Width(320)))
                            {
                                info.mat_id[i] = OBJINFO.id;
                                isDisplay[i] = false;
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                        EditorGUILayout.EndScrollView();
                        EditorGUILayout.EndVertical();
                    }
                }
                EditorGUILayout.EndVertical();

                if (ID_Warning)
                {
                    EditorGUILayout.HelpBox("当前使用的ID已经存在，默认ID为:" + info.id.ToString(), MessageType.Error);
                }
                EditorGUILayout.EndVertical();

            }
        }

        if(GUILayout.Button("保存更改", GUILayout.Width(100)))
        {
            Save_info();
        }
        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndVertical();
        //EditorGUILayout.Separator();
    }

    private void OnDisable()
    {
        //Save_info();
    }

    private void OnInspectorUpdate()
    {
        this.Repaint();
    }

    private void Save_info()
    {
        prop_info.WriteInfo();
        craft_info.WriteInfo();
        buff_info.WriteInfo();
        Debug.Log("已经保存");
    }

    private Sprite LoadSpriteInAsset(string path, string name)
    {
        //Object[] AllSprites = AssetDatabase.LoadAllAssetsAtPath(path);
        if (path == "") return null;

        Object[] AllSprites = Resources.LoadAll(path);
        Sprite target_sprite;

        for (int i = 0; i < AllSprites.Length; i++)
        {
            if (AllSprites[i].name == name)
            {
                if (AllSprites[i].GetType() == typeof(UnityEngine.Sprite))
                {
                    target_sprite = (Sprite)AllSprites[i];
                    return target_sprite;
                }
            }
        }
        return null;
    }
    
    private Texture2D Sprite_To_Texture(Sprite sourceSprite)
    {
        Texture2D prop_image = new Texture2D((int)sourceSprite.rect.width, (int)sourceSprite.rect.height);
        var pixels = sourceSprite.texture.GetPixels
            ((int)sourceSprite.textureRect.x,
            (int)sourceSprite.textureRect.y,
            (int)sourceSprite.textureRect.width,
            (int)sourceSprite.textureRect.height);
        prop_image.SetPixels(pixels);
        prop_image.Apply();

        return prop_image;
    }

}
